package com.gt.userinfo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.gt.userinfo.utils.Constants;
import com.gt.userinfo.utils.Session;
import com.gt.userinfo.utils.User;
import com.gt.userinfo.xml.DomContentAppend;

public class UserDetailViewEditWebView extends Activity {
	User previousUserData;
	String XML_FILE = Constants.XML_FILE;
	String OP_DATA_PATH = Constants.OP_DATA_PATH;
	boolean isEntry;
	WebView webView;
	User returnedUser;
	enum AppStatusJs  {SAVING,BACKPRESS};
	AppStatusJs status;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.userdetailentrywebview);
		initComponents();
		processBundleValue();
	}

	@Override
	public void onBackPressed() {
		status= AppStatusJs.BACKPRESS;
		callGetFormData();
	}

	/**
	 * onCreateOptionsMenu is called only once
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.entry_form_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.backMnu:
			status= AppStatusJs.BACKPRESS;
			callGetFormData();
			return true;
		case R.id.saveDataMnu:
			status= AppStatusJs.SAVING;
			callGetFormData();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void processBundleValue() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			// but extra cannot be null
			isEntry = extras.getBoolean("ISENTRY");
			if (isEntry) {
			} else {
				previousUserData = (User) extras.get("USER");
				displayUserDetail();

			}
		}

	}

	private void displayUserDetail() {

	}

	private void initComponents() {
		webView = (WebView) findViewById(R.id.detailEntryWebView);
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new MyJavaScriptInterface(this), "Android");
		webView.loadUrl("file:///android_res/raw/entryform.html");
		webView.setWebChromeClient(new JsChromeClient());

	}

	public class MyJavaScriptInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		MyJavaScriptInterface(Context c) {
			mContext = c;
		}

		public String sendValueToJs() throws Exception {
			JSONObject json = new JSONObject();
			if (!isEntry) {
				json.put("userName", previousUserData.getUserName());
				json.put("firstName", previousUserData.getFirstName());
				json.put("lastName", previousUserData.getLastName());
				json.put("address", previousUserData.getAddress());
			}
			return (json.toString());
		}

		public void receiveValueFromJs(String obj) throws Exception {
			JSONObject json = new JSONObject(obj);
			returnedUser = new User();
			returnedUser.setUserName(json.getString("userName"));
			returnedUser.setLastName(json.getString("lastName"));
			returnedUser.setFirstName(json.getString("firstName"));
			returnedUser.setAddress(json.getString("address"));
			// returnedUser.set(json.getString("userName"));
			switch(status){
			case  BACKPRESS :
				handleBackPressJs();
				break;
			case  SAVING :
				handleSave();
				break;
			}
		}

		private void handleSave() {
			User user = getFormData();
			if (user.equals(previousUserData)) {
				showToast("Nothing to Save");
			}
			if (saveUserDetail()) {
				handleSuccessSave();
			} else {
				showError();
			}
		}
		public void handleBackPressJs() throws Exception {
			if (!isEntry ||  previousUserData.equals(getFormData())) {
				finish();
			} else {
				DialogInterface.OnClickListener backPressDiOnClickL = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							finish();
							break;

						case DialogInterface.BUTTON_NEGATIVE:
							// No button clicked
							break;
						}
					}
				};
				AlertDialog.Builder builder = new AlertDialog.Builder(UserDetailViewEditWebView.this);
				builder.setMessage("There are unsaved changes,\nSure to Exit ?")
						.setPositiveButton("Yes", backPressDiOnClickL)
						.setNegativeButton("No", backPressDiOnClickL).show();
			}
		}
	}

	private class JsChromeClient extends WebChromeClient {
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				final JsResult result) {
			new AlertDialog.Builder(UserDetailViewEditWebView.this)
					.setTitle("JavaScript Alert !")
					.setMessage(message)
					.setPositiveButton(android.R.string.ok,
							new AlertDialog.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									result.confirm();
								}
							}).setCancelable(false).create().show();

			return true;
		}
	}

	private void showError() {
		// dialog at success
		DialogInterface.OnClickListener saveFailDiOnClickL = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Edit Failed")
				.setPositiveButton("OK", saveFailDiOnClickL).show();

	}

	private boolean saveUserDetail() {
		User user = getFormData();
		DomContentAppend dca = new DomContentAppend(XML_FILE, OP_DATA_PATH
				+ getDate() + user.getUserName().trim() + "_.xml");
		return dca.editUser(user);

	}

	private void showToast(String msg) {
		Toast toast;
		toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
		toast.show();
	}

	private void handleSuccessSave() {
		DialogInterface.OnClickListener saveSuccessDiOnClickL = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		};
		// dialog at success
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Edit Success")
				.setPositiveButton("OK", saveSuccessDiOnClickL).show();

	}

	private void callGetFormData() {
		webView.loadUrl("javascript:returnFormValues()");
	}

	private User getFormData() {
		
		// TODO: add form input for usrname and password also
		// currently set username,password from session
		Session ss = ((Session) getApplicationContext());
		User u = ss.getLoggedInUser();
		returnedUser.setUserName(u.getUserName());
		returnedUser.setPassword(u.getPassword());
		// read value from form
		returnedUser.setPhoneNo("");
		returnedUser.setCreatedDate("");
		returnedUser.setCreatedTime("");

		return returnedUser;
	}

	private static String getDate() {
		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss_");
		Date date = new Date();
		return dateFormat.format(date);
	}

}
